#include "StdAfx.h"
#include "Trick.h"

using namespace SHGame;
using namespace System::Collections::Generic;

/*
Creates a new trick with the given player & card
as the leader & lead. 
*/
Trick::Trick(Player^ leader, Card^ lead) {
	this->map = gcnew Dictionary<Player^, Card^>();
	this->leader = leader;
	this->play(leader, lead);
}

/*
Adds the given player to this trick, having played the
given card. This means that the player played the card.
Returns true if the card was played. If, for example,
the player has already played on this trick or all 5 players
have played, this does nothing and returns false.
*/
bool Trick::play(Player^ p, Card^ c) {
	if (this->map->ContainsKey(p))
		this->map->Remove(p);
	this->map->Add(p, c);
	return true;
}
/*
Gets the card played by the given player.
Returns null if the player has not played.
*/
Card^ Trick::get(Player^ p) {
	return this->map[p];
}

/*
Gets the player that played the given card.
Returns null if the card has not been player
*/
Player^ Trick::get(Card^ c) {
	return nullptr;
}

/*
Checks if the given player has played. Returns true
if the played played, else false. ("playing" means adding
the player and card using the add method).
*/
bool Trick::played(Player^ p) {
	return this->map->ContainsKey(p);
}
/*
Gets the first card played. This is the card that other
players must follow suit with. 
*/
Card^ Trick::getLead() {
	return this->map[this->leader];
}
/*
Gets the number of points on this trick.
*/
int Trick::getPoints() {
	int points = 0;
	IEnumerator<Player^> ^penum = this->map->Keys->GetEnumerator();
	while (penum->MoveNext()) {
		Player^ p = penum->Current;
		Card^ c = this->get(p);
		points += c->getValue();
	}
	return points;
}

Player^ Trick::getLeader() {
	return this->leader;
}

Player^ Trick::getOwner() {
	if (this->leader == nullptr)
		return nullptr;
	Card^ lead = this->getLead();
	Player^ owner = this->leader;
	Card^ owner_card = lead;
	IEnumerator<Player^> ^penum = this->map->Keys->GetEnumerator();
	while (penum->MoveNext()) {
		Player^ p = penum->Current;
		Card^ c = this->get(p);
		if (c == nullptr)
		{
			continue;
		}
		// check if its on suit:
		if (c->onSuit(lead)) {
			// check if its "bigger"
			if (c->getRank() > owner_card->getRank()) {
				owner_card = c;
				owner = p;
			}
		} else {
			// only consider off-suit cards if they are trump
			if (c->isTrump()) {
				if (c->getRank() > owner_card->getRank()) {
					owner_card = c;
					owner = p;
					
				}
			}
		}
	}
	return owner;
}
bool Trick::Finished() {
	return this->map->Count >= NUM_PLAYERS;
}